
package com.jf.cloud.service.sysmanager.support.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.jf.cloud.service.sysmanager.common.db.BaseDao;
import com.jf.cloud.service.sysmanager.common.db.jdbc.RowMapperFactory;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.entity.PubgUser;
import com.jf.cloud.service.sysmanager.support.entity.Result;

/**
 * 基础业务数据处理器
 * 
 * @author 朱建文 创建时间：2018年4月3日 下午6:30:03
 */
@Service("baseDataBizHandler")
public class BaseDataBizHandler {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(BaseDataBizHandler.class);

	/**
	 * JDBC公共DAO
	 */
	@Resource
	private BaseDao baseDao;

	/**
	 * 根据表名、主键判断对象是否存在
	 * 
	 * @author 朱建文 创建时间：2018年4月3日 下午6:30:11
	 */
	public boolean isExist(String tableName, Long rowId) {
		String sql = "SELECT COUNT(0) FROM " + tableName + " WHERE ROW_ID = ? ";
		return this.baseDao.find(sql, Long.class, rowId) > 0;
	}

	/**
	 * 检查邀请码是否重复
	 * 
	 * @author 朱建文 创建时间：2018年4月3日 下午2:52:04
	 */
	public boolean checkClubInvitelCodeIsExist(Long rowId, String inviteCode) {
		String sql = " SELECT COUNT(0) FROM pubg_club WHERE INVITE_CODE = ?";
		if (rowId != null) {
			sql += " AND ROW_ID <> " + rowId;
		}
		int count = this.baseDao.findCount(sql, inviteCode);
		if (count > 0) {
			return true;
		}
		return false;
	}
	
	/**
	 * 检查邀请码是否重复
	 * 
	 * @author 朱建文 创建时间：2018年4月3日 下午2:52:04
	 */
	public boolean checkTeamInvitelCodeIsExist(Long rowId, String inviteCode) {
		String sql = " SELECT COUNT(0) FROM pubg_team WHERE INVITE_CODE = ? ";
		if (rowId != null) {
			sql += " AND ROW_ID <> " + rowId;
		}
		int count = this.baseDao.findCount(sql, inviteCode);
		if (count > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 获取战队字典列表
	 * 
	 * @author 朱建文 创建时间：2018年4月3日 下午1:26:29
	 */
	public List<Map<String, Object>> getPubgTeamDictList(PubgUser pubgUser) {
		List<Map<String, Object>> datalList = new ArrayList<Map<String,Object>>();
		try {
			StringBuffer sb = new StringBuffer(255);
			if (pubgUser.getUserRole().equals(UserConstant.USER_ROLE_10.getId())) {
				sb.append(" SELECT ");
				sb.append("   b.TEAM_ID value, b.TEAM_NAME label1");
				sb.append(" FROM ");
				sb.append("   pubg_user_team b ");
				sb.append(" WHERE ");
				sb.append("   b.USER_ID = ? AND RELATION_STATE = 2 ");
				datalList = this.baseDao.findMapList(sb.toString(), pubgUser.getRowId());
				
			} else if (pubgUser.getUserRole().equals(UserConstant.USER_ROLE_20.getId())) {
				sb.append(" SELECT ");
				sb.append("   b.ROW_ID value, b.TEAM_NAME label1, b.TEAM_NO label2");
				sb.append(" FROM ");
				sb.append("   pubg_team b ");
				sb.append(" WHERE ");
				sb.append("   b.CAPTAIN_ID LIKE '%" + pubgUser.getRowId() + ",%'");
				datalList = this.baseDao.findMapList(sb.toString());
				
			} else if (pubgUser.getUserRole().equals(UserConstant.USER_ROLE_30.getId())) {
				sb.append(" SELECT ROW_ID ");
				sb.append(" FROM pubg_club b ");
				sb.append(" WHERE b.MINISTER_ID LIKE '%" + pubgUser.getRowId() + ",%'");
				long clubId = this.baseDao.find(sb.toString(), Long.class);
				
				sb = new StringBuffer(255);
				sb.append(" SELECT ");
				sb.append("   b.ROW_ID value, b.TEAM_NAME label1, b.TEAM_NO label2");
				sb.append(" FROM ");
				sb.append("   pubg_team b ");
				sb.append(" WHERE ");
				sb.append("   b.CLUB_ID = ? ");
				datalList = this.baseDao.findMapList(sb.toString(), clubId);
			}
		} catch (DataAccessException e) {
			log.error("获取战队字典列表出错！", e);
		}
		return datalList;
	}

	/**
	 * 获取战队字典列表
	 * 
	 * @author 朱建文 创建时间：2018年4月27日 下午4:56:45
	 */
	public List<Map<String, Object>> getTeamDictList(Long clubId){
		List<Map<String, Object>> datalList = new ArrayList<Map<String,Object>>();
		StringBuffer sb = new StringBuffer(255);
		sb.append(" SELECT ");
		sb.append("   b.ROW_ID value, b.TEAM_NAME label1, b.TEAM_NO label2");
		sb.append(" FROM ");
		sb.append("   pubg_team b ");
		sb.append(" WHERE ");
		sb.append("   b.CLUB_ID = ? ");
		datalList = this.baseDao.findMapList(sb.toString(), clubId);
		return datalList;
	}
	
	/**
	 * 根据帐号名称获取帐号ID
	 * @param account 帐号
	 * @param userRole 用户角色
	 * @param id 战队ID、俱乐部ID
	 * 
	 * @author 朱建文 创建时间：2018年4月3日 下午3:45:46
	 */
	public Result<String> bulidUserIdByAccount(Result<String> result, String account, Integer userRole, Long id){
		try {
			result.setCode(-1);
			if (account == null) {
				result.setMessage("帐号名称为空！");
				return result;
			}
			String[] accountS = null;
			if (account.indexOf(",") < 0) {
				accountS = new String[]{account};
			} else {
				accountS = account.split(",");
			}
			
			// 帐号是否存在sql
			String isExistSql = "SELECT * FROM pubg_user WHERE USER_ACCOUNT = ?";
			
			// 用户关系sql
			String sql = "SELECT COUNT(0) FROM pubg_user_team WHERE USER_ID = ? AND RELATION_STATE IN (1,2)";
			String userTeamSql = "";
			if (id != null) {
				sql += " AND TEAM_ID <> " + id;
				userTeamSql += " AND TEAM_ID <> " + id;
			}
			if (userRole.equals(UserConstant.USER_ROLE_30.getId())) {
				sql = "SELECT COUNT(0) FROM pubg_user_club WHERE USER_ID = ? AND RELATION_STATE IN (1,2) ";
				if (id != null) {
					sql += " AND CLUB_ID <> " + id;
				}
			}
			
			String userIds = "";
			PubgUser pubgUser = null;
			int userRelation = 0;
			for (int i = 0; i < accountS.length; i++) {
				pubgUser = this.baseDao.findObject(isExistSql, RowMapperFactory.newInstance(PubgUser.class), accountS[i]);
				
				// 验证帐号是否存在
				if (pubgUser == null) {
					result.setMessage("【" + accountS[i] + "】不存在！");
					return result;
				}
				
				// 当前帐号的角色
				if (UserConstant.USER_ROLE_30.getId().intValue() == pubgUser.getUserRole() ) {
					result.setMessage("【" + accountS[i] + "】目前是部长！");
					return result;
				}
				
				if (UserConstant.USER_ROLE_20.getId().intValue() == pubgUser.getUserRole() ) {
					
					// 当前帐号和其他俱乐部/战队是否存在关系
					userTeamSql = "SELECT COUNT(0) FROM pubg_team WHERE CAPTAIN_ID LIKE '%" + pubgUser.getRowId() + ",%'";
					if (id != null) {
						userTeamSql += " AND ROW_ID <> " + id;
					}
					userRelation = this.baseDao.findCount(userTeamSql);
					if (userRelation > 0) {
						result.setMessage("【" + accountS[i] + "】是其他战队的队长！");
						return result;
					}
				}
				
				// 当前帐号和其他俱乐部/战队是否存在关系
				userRelation = this.baseDao.findCount(sql, pubgUser.getRowId());
				if (userRelation > 0) {
					result.setMessage("【" + accountS[i] + "】队员和其他俱乐部/战队存在关系！");
					return result;
				}
				
				// 当前帐号是否有余额
				if (pubgUser.getBalance() != null && pubgUser.getBalance() > 0) {
					result.setMessage("【" + accountS[i] + "】队员余额不为空！");
					return result;
				}
				userIds += pubgUser.getRowId() + ",";
			}
			result.setCode(1);
			result.setData(userIds);
		} catch (Exception e) {
			log.error("根据帐号名称获取帐号ID出错！", e);
		}
		return result;
	}
	
}
